package com.cysion.study.ui

import android.annotation.SuppressLint
import android.app.Activity
import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.os.StrictMode
import android.provider.MediaStore
import android.support.v4.content.res.ResourcesCompat
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.cysion.other.color
import com.cysion.study.ktbox.Box
import com.cysion.study.ktbox.Box.context
import com.cysion.study.ktbox.base.BaseActivity
import com.cysion.study.ktbox.image.RoundTransform
import com.cysion.study.ktbox.net.BaseResponseRx
import com.cysion.study.ktbox.net.ErrorHandler
import com.cysion.study.ktbox.utils.ACache
import com.cysion.study.ktbox.utils.CLog
import com.cysion.other.startActivityForResult_ex
import com.cysion.targetfun._subscribe
import com.cysion.study.uibox.bar.TopBar
import com.cysion.study.uibox.dialog.Alert
import com.cysion.study.R
import com.cysion.study.helper.UserCache
import com.cysion.study.ktbox.utils.darkTextTheme
import com.cysion.study.net.ApiClient
import com.cysion.study.net.Urls
import com.cysion.study.ui.fragment.MyapplysActivity
import com.cysion.study.uibox.dialog.AlertSearch
import com.cysion.study.widget.*
import com.cysion.study.widget.ImageUtils.getAbsoluteImagePath
import com.cysion.study.widget.http.HttpUtil
import com.loopj.android.http.JsonHttpResponseHandler
import com.loopj.android.http.RequestParams
import kotlinx.android.synthetic.main.activity_approval.*
import kotlinx.android.synthetic.main.activity_approval.fl_pics
import kotlinx.android.synthetic.main.activity_approval.topbar
import kotlinx.android.synthetic.main.activity_comment_detail.*
import kotlinx.android.synthetic.main.activity_feedback.*
import org.json.JSONObject
import java.io.*
import java.text.SimpleDateFormat
import java.util.*

class ApprovalActivity : BaseActivity(), View.OnClickListener, PicChooserDialog.OnPicChooserListener {



    override fun getLayoutId(): Int = R.layout.activity_approval

    override fun initView() {
        darkTextTheme(color(R.color.white))
        topbar.apply {
            setTitle("我的申请")
            setTitleBackColor(color(R.color.white))
            setImageRes(R.mipmap.history,TopBar.Pos.RIGHT)
//            setImageRes(R.mipmap.icon_back,TopBar.Pos.LEFT)
            setOnTopBarClickListener { obj, pos ->
                if (pos == TopBar.Pos.LEFT) {
                    finish()
                }else if (pos == TopBar.Pos.RIGHT) {
                    UIHelper.jump(self, MyapplysActivity::class.java)

                }
            }
        }
        tv_qj.setOnClickListener(this)
        tv_bx.setOnClickListener(this)
        tv_tx.setOnClickListener(this)
        tvNext.setOnClickListener(this)

        iv_st1.setOnClickListener(this)
        iv_st2.setOnClickListener(this)

        flow.removeAllViews()
        initAdd()
        coty_flow.removeAllViews()
        initCory()
        inViewq()//默认请假tab页面

        //获取日历的一个对象
        cal = Calendar.getInstance()
        //获取年月日时分秒的信息
        year = cal.get(Calendar.YEAR)
        //month从0开始计算(一月month = 0)
        month = cal.get(Calendar.MONTH) + 1
        day = cal.get(Calendar.DAY_OF_MONTH)
        hour = cal.get(Calendar.HOUR_OF_DAY)
        minute = cal.get(Calendar.MINUTE)
        initPhotoError()
        initFlowLayoutForPulishListener()
    }
    private fun initPhotoError() {
        // android 7.0系统解决拍照的问题
        var builder =  StrictMode.VmPolicy.Builder()
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();
    }
    private val selectPics = ArrayList<String>()
    private fun initFlowLayoutForPulishListener() {
//        fl_pics.setShow(false)
        fl_pics.setonFlowLayoutForPulishListener(object :
            FlowLayoutForPulish.OnFlowLayoutForPulishListener {
            override fun add() {
                if (selectPics.size >= 3) {
                    ShowToast("最多不能超过3张图片")
                    return
                }
                takePhoto()
            }

            override fun delete(item: FlowLayoutForPulish.Item) {
                selectPics.removeAt(item.index)
            }

            override fun onClick(item: FlowLayoutForPulish.Item) {
                val list = ArrayList<String>()
                list.add(item.path)
//                list.add(getFileUrl(item.path))
                //                PhotoPagerActivity.gotoActivity(_activity, list, 0);//预览大图
            }
        })
    }

    fun takePhoto() {
        val dialog = PicChooserDialog(this, R.style.bottom_dialog)
        dialog.setListner(this)
        dialog.show()
    }


    internal var addStid = StringBuilder()
    internal var copyStid = StringBuilder()


    private var protraitPath: String? = null
    private var protraitFile: File? = null
    private var protraitBitmap: Bitmap? = null


//    private var addList: MutableList<StaffList> = mutableListOf()
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        //301审批
        if (requestCode == 301 && resultCode == Activity.RESULT_OK) {
//            val result = data?.getParcelableArrayListExtra<StaffList>("key")
//            addList = result!!
            addStid = StringBuilder()
            /*for (it in result!!) {
                addStid.append("," + it.stid)
                if (addStid.isNotEmpty()) {
                    addStid.deleteCharAt(0)
                }
                var name = it.stName
                addGroup(it)
            }*/
            initAdd()

        } else if (requestCode == 401 && resultCode == Activity.RESULT_OK) {//抄送
//            val result = data?.getParcelableArrayListExtra<Staffs>("key")
            copyStid = StringBuilder()
            /*for (it in result!!) {
                copyStid.append("," + it.stid)
                if (copyStid.isNotEmpty()) {
                    copyStid.deleteCharAt(0)
                }
                var name = it.stName
                var url = it.headImageUrl
                addCopyGroup(name, url)
            }*/
            initCory()
            /*copyStid = data?.getBundleExtra("key")?.getString("sb").toString()
            var name = data?.getBundleExtra("key")?.getString("name")
            var url = data?.getBundleExtra("key")?.getString("url")
            addCopyGroup(name, url)*/
        }else if (requestCode == 10) {
            val uri = data!!.data
            if (uri != null) {
                protraitPath = getAbsoluteImagePath(this, uri)
                protraitFile = File(protraitPath)
                //outputBitmap(null,ImageUtils.getAbsoluteImagePath(this, uri));
            }
            if (uri == null) {
                //use bundle to get data
                val bundle = data.extras
                if (bundle != null) {
                    val photo = bundle.get("data") as Bitmap //get bitmap
                    //spath :生成图片取个名字和路径包含类型
                    setBitmapTempFile(photo)
                } else {
                    ShowToast("获取图片错误")
                    return
                }
            }
            // 获取头像缩略图
            if (!TextUtils.isEmpty(protraitPath) && protraitFile!!.exists()) {
                protraitBitmap = ImageUtils.getBitmapByPath(protraitPath)
                protraitPath = compressImage(protraitPath.toString())
                outputBitmap(protraitBitmap!!, protraitPath!!)
            }
        }else if (requestCode == 11) {
            if (imageName != null) {
                val degree = PhotoUtils.readPictureDegree(imageName)
                val bitmap = FileCompressUtil.com(imageName)
                if (bitmap != null) {
                    val newbitmap = PhotoUtils.rotaingImageView(
                        degree,
                        bitmap
                    )
                    val mCompressPhotopath = PhotoUtils.saveBitmap2file(
                        newbitmap, System.currentTimeMillis().toString() + ".jpg"
                    )
                    if (TextUtils.isEmpty(mCompressPhotopath)) {
                        return
                    }
                    val file = File(mCompressPhotopath)
                    //                            updateAvatarInServer(file);
                    protraitBitmap = ImageUtils.getBitmapByPath(mCompressPhotopath)
                    outputBitmap(protraitBitmap!!, mCompressPhotopath)
                }

            }
        }

    }
    fun outputBitmap(bitmap: Bitmap, path: String) {
        println("#####选择图片=" + path)
        if (TextUtils.isEmpty(path)) {
            return
        }
        uploadPic(path)
    }
    private var index = 0
    private fun uploadPic(headUrl: String) {
        val params = RequestParams()
        params.put("file", File(headUrl))
        params.put("token", ACache.get(Box.context).getAsString("token"))
        HttpUtil.post1(Urls.uploadPicture, params, object : JsonHttpResponseHandler() {
            override fun onSuccess(statusCode: Int, headers: Array<out org.apache.http.Header>?, response: JSONObject?) {
                super.onSuccess(statusCode, headers, response)
                Alert.close()
                try {
                    if (response?.getString("code") == "0") {
                        println("上传图片返回=${response.getString("data")}")
//                        var obj: String? = response.getString("data")
                        var imaPath = response.getString("data")
                        println("图片地址=${imaPath}")
                        selectPics.add(imaPath)//把图片添加到list
//                        fl_pics.addLocationPic(index, true, headUrl)//显示图片
                        fl_pics.setShowData(false,selectPics,false,true)
                        index++
                    } else {
                        ShowToast("上传失败")
                        Alert.close()
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                } finally {
                    Alert.close()
//                    ShowDialog.dissmiss()
                }
            }
            override fun onFinish() {
                Alert.close()
            }

            override fun onFailure(statusCode: Int, headers: Array<out org.apache.http.Header>?, responseString: String?, throwable: Throwable?) {
                super.onFailure(statusCode, headers, responseString, throwable)
                Alert.close()
            }
        })
    }

    var type: String = "0"//审批类型: 0.请假 1.报销 2.调休
    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tv_qj -> {//请假
//                tv_qj.background = resources.getDrawable(R.drawable.login_bg)
                inViewq()
                type = "0"
            }
            R.id.tv_bx -> {//报销
                type = "1"
                inViewb()
            }
            R.id.tv_tx -> {//调休
                type = "2"
                inViewt()
            }
            R.id.tvNext -> {//
                et_yj.checkBlank("申请人不能为空") ?: return
                if (TextUtils.isEmpty(addStid)) {
                    ShowToast("请添加审批人")
                    return
                }
                if (TextUtils.isEmpty(copyStid)) {
                    ShowToast("请添加抄送人")
                    return
                }
                if (type == "2") {
                    et_4.checkBlank("请填写报销使用时间") ?: return
                }

                submit()
            }
            R.id.iv_st1 -> {
                dialog("1")
            }
            R.id.iv_st2 -> {
                dialog("2")
            }
        }
    }

    internal var pics = StringBuilder()
    private fun submit() {
        var name = et_yj.text.toString().trim()
        var remark = et_content.text.toString().trim()
        var starTime = ""
        var money = ""
        if (type == "2") {
            starTime = ""
            money = tv_st1.text.toString().trim()
        } else {
            starTime = tv_st1.text.toString().trim()
            money=""
        }
        var end = tv_st2.text.toString().trim()
        var useTime=""
        var totalTime=""
        if (type == "1") {
            useTime = et_4.text.toString().trim()
        } else {
            totalTime =et_4.text.toString().trim()
        }

        for (i in selectPics.indices) {
            pics.append("," + selectPics[i])
        }
        if (pics.isNotEmpty()) {
            pics.deleteCharAt(0)
        } else {
            //            AppContext.showToast("请选择");
            //            return;
        }

        Alert.loading(self)
        //type 类型:0.注册 1.修改登录密码 2.修改支付密码 3.登陆密码 4.修改手机号码
        ApiClient.api.approvalRelease(UserCache.token, type, name, remark, starTime, end, addStid.toString(), copyStid.toString(), pics.toString(),money,useTime,totalTime)
            .compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
                     ShowToast("提交成功")
                    finish()
                }
                _onError {
                    Alert.close()
                    val handle = ErrorHandler.handle(it)
                    ShowToast(handle.errorMsg)
                }
            }
    }

    fun compressImage(picFileName: String): String {
        val bitmap = BitmapUtil.decodeFile(picFileName, 960)
        val baos = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos)// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        var options = 90f
        while (baos.toByteArray().size / 1024 > 200 && options > 80) { // 循环判断如果压缩后图片
            baos.reset()// 重置baos即清空baos
            bitmap.compress(Bitmap.CompressFormat.JPEG, options.toInt(), baos)// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 5f// 每次都减少10
        }
        val file = FileUtils.createFileWithSuffix(".jpg", this)
        println("压缩后大小 " + baos.toByteArray().size / 1024 + "==options=" + options)
        // 保存新文件
        try {
            val out = FileOutputStream(file)
            out.write(baos.toByteArray())
            out.flush()
            out.close()
            return file.getAbsolutePath()
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
            return ""
        } catch (e: IOException) {
            e.printStackTrace()
            return ""
        }
    }

    private val  FILE_SAVEPATH: String = Environment.getExternalStorageDirectory().absolutePath
    private var cropUri: Uri? = null
    private var origUri: Uri? = null
    private fun setBitmapTempFile(bitmap: Bitmap): Uri? {
        val storageState = Environment.getExternalStorageState()
        if (storageState == Environment.MEDIA_MOUNTED) {
            val savedir = File(FILE_SAVEPATH)
            if (!savedir.exists()) {
                savedir.mkdirs()
            }
        } else {
            ShowToast("无法保存上传的头像，请检查SD卡是否挂载")
            return null
        }
        val timeStamp = SimpleDateFormat("yyyyMMddHHmmss")
            .format(Date())
        // 照片命名
        val cropFileName = "osc_camera_$timeStamp.jpg"
        // 裁剪头像的绝对路径
        protraitPath = FILE_SAVEPATH + cropFileName
        protraitFile = File(protraitPath)
        try {
            ImageUtils.saveImage(this, protraitPath, bitmap)
        } catch (e: IOException) {
            e.printStackTrace()
        }

        cropUri = Uri.fromFile(protraitFile)
        this.origUri = this.cropUri
        return this.cropUri
    }

    //选择图片回调 start
    override fun onClickFromGallery(view: View?) {
        startImagePick()

    }

    override fun onClickFromCamera(view: View?) {
        startActionCamera()
    }
    //选择图片回调 end

    /**
     * 选择图片裁剪
     *
     */
    private fun startImagePick() {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        startActivityForResult(
            Intent.createChooser(intent, "选择图片"), 10
        )
    }
    private var imageName: String? = null
    /**
     * 相机拍照
     *
     */
    private fun startActionCamera() {
        val SAVE_PIC_PATH = Environment.getExternalStorageDirectory().absolutePath + "/Buyers/saveImage/"

        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        val dir = File(SAVE_PIC_PATH)
        if (!dir.exists()) {
            dir.mkdirs()
        }
        imageName = SAVE_PIC_PATH + getNowTime() + ".png"

        val file = File(imageName!!)
        if (!file.exists()) {
            try {
                file.createNewFile()
            } catch (e: IOException) {

            }

        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file))
        startActivityForResult(intent, 11)
    }
    //获取当前时间
    @SuppressLint("SimpleDateFormat")
    private fun getNowTime(): String {
        val date = Date(System.currentTimeMillis())
        val dateFormat = SimpleDateFormat("MMddHHmmssSS")
        return dateFormat.format(date)
    }

    var start: String = ""
    var end: String = ""
    lateinit var cal: Calendar
    var year: Int = 0
    var month: Int = 0
    var day: Int = 0
    var hour: Int = 0
    var minute: Int = 0
    private fun dialog(type: String) {
        val timeDialog = TimePickerDialog(
            this,
            TimePickerDialog.OnTimeSetListener { tp, hourOfDay, minute ->
                if ("1" == type) {
                    start =
                        start + "  " + (if (hourOfDay < 10) "0$hourOfDay" else hourOfDay) + ":" + (if (minute < 10) "0$minute" else minute) + ":" + "00"
                    tv_st1.setText(start)
                } else if ("2" == type) {
                    end =
                        end + "  " + (if (hourOfDay < 10) "0$hourOfDay" else hourOfDay) + ":" + (if (minute < 10) "0$minute" else minute) + ":" + "00"
                    tv_st2.setText(end)
                }
                CLog.i("时间=$start--end=$end")
            }, hour, minute, true
        )
        timeDialog.setTitle("请选择时间")
        timeDialog.show()


        val dateDialog = DatePickerDialog(
            this,
            DatePickerDialog.OnDateSetListener { dp, year, month, dayOfMonth ->
                CLog.i("年ssss=" + year + "--月=" + (if (month + 1 < 10) "0" + (month + 1) else month + 1) + "---日=" + if (dayOfMonth < 10) "0$dayOfMonth" else dayOfMonth)
                //2017-12-04 12：00：00
                if ("1" == type) {
                    start =
                        year.toString() + "-" + (if (month + 1 < 10) "0" + (month + 1) else month + 1) + "-" + if (dayOfMonth < 10) "0$dayOfMonth" else dayOfMonth
                } else if ("2" == type) {
                    end =
                        year.toString() + "-" + (if (month + 1 < 10) "0" + (month + 1) else month + 1) + "-" + if (dayOfMonth < 10) "0$dayOfMonth" else dayOfMonth
                }
            }, year, cal.get(Calendar.MONTH), day
        )
        dateDialog.setTitle("请选择日期")
        dateDialog.show()
    }


    private fun addCopyGroup(name: String?, url: String?) {

        val iv = LayoutInflater.from(this).inflate(R.layout.flow_layout, coty_flow, false)

        var ivAdd = iv.findViewById<ImageView>(R.id.iv_head)
        var tvname = iv.findViewById<TextView>(R.id.tv_name)
        tvname.visibility = View.VISIBLE
        tvname.text = name
        var ivdel = iv.findViewById<ImageView>(R.id.iv_detele)
        ivdel.setOnClickListener {
            coty_flow.removeView(iv)

        }
        CLog.i("图片=$url")
        Glide.with(context).load(url)
            .apply(RequestOptions.placeholderOf(R.mipmap.default_head))
            .apply(RequestOptions.bitmapTransform(RoundTransform(6)))
            .into(ivAdd)
        coty_flow.addView(iv)

    }

    private fun initCory() {
        val iv = LayoutInflater.from(this).inflate(R.layout.flow_layout, coty_flow, false)
        iv.findViewById<ImageView>(R.id.iv_detele).visibility = View.GONE
        var ivAdd = iv.findViewById<ImageView>(R.id.iv_head)
        var tv_name = iv.findViewById<TextView>(R.id.tv_name)
        tv_name.setText("添加抄送人")
        ivAdd.background = resources.getDrawable(R.mipmap.add_per)
        ivAdd.setOnClickListener {
            //                startActivity_ex<FriendActivity>()
            coty_flow.removeAllViews()
            var bundle = Bundle()
            bundle.putString("type", "2")
            startActivityForResult_ex<FriendActivity>("type",bundle,401)//选择抄送人员
        }

        coty_flow.addView(iv)

    }

    private fun initAdd() {
        val iv = LayoutInflater.from(this).inflate(R.layout.flow_layout, flow, false)
        var ivAdd = iv.findViewById<ImageView>(R.id.iv_head)
        var tv_name = iv.findViewById<TextView>(R.id.tv_name)
        tv_name.setText("添加审批人")
        iv.findViewById<ImageView>(R.id.iv_detele).visibility = View.GONE
        ivAdd.background = resources.getDrawable(R.mipmap.add_per)
        ivAdd.setOnClickListener {
            //                startActivity_ex<FriendActivity>()
            flow.removeAllViews()
            var bundle = Bundle()
            bundle.putString("type", type)
            startActivityForResult_ex<AppFriendActivity>("type",bundle,301)//选择审批人员
        }

        flow.addView(iv)

    }
//    private val pepoList: MutableList<PepoEntity> = mutableListOf()

    private var addIndex = -1



    private fun inViewq() {
        tv_qj.background = ResourcesCompat.getDrawable(getResources(), R.drawable.tab1, null)
        tv_bx.background = ResourcesCompat.getDrawable(getResources(), R.drawable.white_bg, null)
        tv_tx.background = null
        tv_qj.setTextColor(resources.getColor(R.color.white))
        tv_bx.setTextColor(resources.getColor(R.color.main_cl))
        tv_tx.setTextColor(resources.getColor(R.color.main_cl))
        tv_tag1.text = "请假人"
        et_yj.hint = "请填写请假人"
        tv_tag2.text = "请假时间"
        tv_st1.hint = "请选择请假开始时间"
        tv_st2.hint = "请选择请假结束时间"
        tv_tag3.text = "请假时长"
        et_4.hint = "请输入请假时长"
        tv_tag4.text = "请假缘由"
        et_content.hint = "请填写请假缘由"
        iv_st1.visibility = View.VISIBLE
        tv_st2.visibility = View.VISIBLE
        iv_st2.visibility = View.VISIBLE
    }

    private fun inViewb() {
        tv_qj.background = null
        tv_bx.background = ResourcesCompat.getDrawable(getResources(), R.drawable.tab2, null)
        tv_tx.background = null
        tv_qj.setTextColor(resources.getColor(R.color.main_cl))
        tv_bx.setTextColor(resources.getColor(R.color.white))
        tv_tx.setTextColor(resources.getColor(R.color.main_cl))
        tv_tag1.text = "报销人"
        et_yj.hint = "请填写报销人"
        tv_tag2.text = "报销金额"
        tv_st1.hint = "请填写报销金额"
        tv_st1.text = ""
        tv_st2.hint = "请选择请假结束时间"
        tv_tag3.text = "使用时间"
        et_4.hint = "请填写使用时间"
        tv_tag4.text = "报销缘由"
        et_content.hint = "请填写报销缘由"
        iv_st1.visibility = View.GONE
        tv_st2.visibility = View.GONE
        iv_st2.visibility = View.GONE
    }

    private fun inViewt() {
        tv_qj.background = null
        tv_bx.background = ResourcesCompat.getDrawable(getResources(), R.drawable.white_bg, null)
        tv_tx.background = ResourcesCompat.getDrawable(getResources(), R.drawable.tab3, null)
        tv_qj.setTextColor(resources.getColor(R.color.main_cl))
        tv_bx.setTextColor(resources.getColor(R.color.main_cl))
        tv_tx.setTextColor(resources.getColor(R.color.white))
        tv_tag1.text = "申请"
        et_yj.hint = "请填写申请人"
        tv_tag2.text = "调休时间段"
        tv_st1.hint = "请填写报销金额"
        tv_st2.hint = "请选择请假结束时间"
        tv_tag3.text = "总时长"
        et_4.hint = "请填写总时长"
        tv_tag4.text = "申请缘由"
        et_content.hint = "请填写申请缘由"
        iv_st1.visibility = View.VISIBLE
        tv_st2.visibility = View.GONE
        iv_st2.visibility = View.GONE
    }

    override fun closeMvp() {
    }

}
